import os

g_path = ()

def getExecutableExts():
    """Return executable file extensions for current operating system."""
    if os.name in ("nt", "ce"):
        _rv = (".exe", ".bat", ".com")
    else:
        _rv = ("", ".sh")
    return _rv

def findExecutableFile(name):
    """Return full path to given executable file.

    (`name` must lack file extension).

    """
    for _dir in g_path:
        _files = [_name
            for _name in os.listdir(_dir)
            if \
                os.path.isfile(os.path.join(_dir, _name)) and \
                os.path.splitext(_name.lower())[1] in getExecutableExts()
        ]
        for _file in _files:
            _fname = os.path.split(_file)[1]
            _fname = os.path.splitext(_fname)[0]
            if _fname == name:
                return os.path.join(_dir, _file)
    return None

def escapeArg(data):
    """Escape special symbols in command-line argument."""
    _rv = data
    for _ch in ("\\", " "):
        _rv.replace(_ch, "\\" + _ch)
    return _rv

def escapeAllArgs(args):
    """Escape all args in given iterable."""
    return map(escapeArg, args)

def normalizeFilename(name):
    """Remove all non-filename symbols from given `name`."""
    _rv = name
    for _sym in (" ", "\\", "/"):
        _rv = _rv.replace(_sym, "_")
    return _rv

def emptyDir(top):
    """

    Delete everything reachable from the directory named in 'top',
    assuming that symbolic links are files.

    """
    # CAUTION:  This is dangerous!  For example, if top == '/', it
    # could delete all your disk files.
    for (_root, _dirs, _files) in os.walk(top, topdown=False):
        for _name in _files:
            os.remove(os.path.join(_root, _name))
        for _name in _dirs:
            os.rmdir(os.path.join(_root, _name))

def getDefaultSavedFileDir():
    """

    Return directory name that all plugins must use as
    default for storing user files.

    """
    import wx
    return wx.StandardPaths.Get().GetDocumentsDir()


# called upon program init
def initModule(app):
    import sys
    _path = os.getenv("PATH").split(os.pathsep)
    # note that programs' binary dir comes first
    _normPath = [os.path.realpath(app.getSysOpt("binaryDir"))]
    for _el in _path:
        _el = os.path.realpath(_el)
        if _el not in _normPath:
            _normPath.append(_el)
    global g_path
    g_path = _normPath
    app.log_info("Binary file path set to %s", g_path)

# vim: set sts=4 sw=4 et :
